<template lang="pug">
div
  Select(
    :value='user.name'
    ref='autocomplete'
    filterable
    remote
    :remote-method='searchUser'
    :loading='searching'
    @on-change='onSelectUser'
  )
    Option(
      v-for='item in searchResult',
      :key='item.id',
      :value='item.id',
      :label='item.name',
      :disabled='item.binded')
      Avatar.va-middle(:src='item.avatar', icon='person', size='small')
      span.va-middle(style='margin-left: 5px') {{ item.name }}
      span(v-show='item.binded') （已绑定）
</template>

<script>
// import { mapState } from 'vuex'
import Api from '@/apis'

export default {
  timer: null,
  model: {
    prop: 'user',
    event: 'select'
  },
  props: {
    user: { type: Object }
  },
  data () {
    return {
      members: [],
      searching: false,
      searchResult: []
    }
  },
  mounted () {
    Api.Group.getGroupMemberList(this.$store.state.app.id)
      .then(data => {
        this.members = data.data.map(item => item.user.id)
      })
  },
  destroyed () {
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    onSelectUser (val) {
      const user = this.searchResult.find(item => item.id === val)
      user && this.$emit('select', user)
    },
    searchUser (val) {
      clearTimeout(this.timer)
      this.searching = true
      this.timer = setTimeout(() => {
        Api.User.search(val).then(data => {
          // console.log(data)
          this.searchResult = data.map(item => {
            item.binded = this.members.indexOf(item.id) > -1
            return item
          })
          // this.acOpts = data.map(item => item.name) || []
          this.searching = false
        })
      }, 300)
    }
  }
}
</script>
